package com.ps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ps.constant.JwtClaimsConstant;
import com.ps.constant.MessageConstant;
import com.ps.constant.PasswordConstant;
import com.ps.constant.StatusConstant;
import com.ps.dto.EmployeeDTO;
import com.ps.dto.EmployeeLoginDTO;
import com.ps.dto.EmployeePageQueryDTO;
import com.ps.entity.Employee;
import com.ps.exception.AccountLockedException;
import com.ps.exception.AccountNotFoundException;
import com.ps.exception.PasswordErrorException;
import com.ps.mapper.EmployeeMapper;
import com.ps.properties.JwtProperties;
import com.ps.result.PageResult;
import com.ps.result.Result;
import com.ps.service.EmployeeService;
import com.ps.utils.JwtUtil;
import com.ps.vo.EmployeeLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ps.constant.SystemConstant.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Autowired
    private  EmployeeMapper employeeMapper;
    @Autowired
    private  JwtProperties jwtProperties;
    @Override
    public void save(EmployeeDTO employeeDTO) {
        if (employeeDTO == null) {
            throw new IllegalArgumentException(EMPLOYEE_IS_NULL);
        }
        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        try {
            save(employee);
            Long id = employee.getId();
        } catch (Exception e) {
            // 可选择抛出自定义异常，通知上层处理
            throw new RuntimeException(ERROR_SAVE_EMPLOYEE, e);
        }
    }

    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        Employee employee = query().eq("username", username).one();;
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对前端传过来的铭文进行加密
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
    //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        //3、返回实体对象
        return EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page=employeeMapper.pageQuery(employeePageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    // 重写父类方法，根据传入的status和id更新员工状态
    public void starOrStop(Integer status, Long id) {
        // 创建Employee对象，设置status和id属性
        Employee employee=Employee.builder()
                .status(status)
                .id(id)
                .build();
        // 更新员工状态
        lambdaUpdate()
                .set(Employee::getStatus,employee.getStatus())
                .eq(Employee::getId,employee.getId())
                .update();
    }

    @Override
    public Employee getToId(Long id) {
        Employee employee = getById(id);
        if (employee == null) {
            throw new RuntimeException(EMPLOYEE_ID_NULL + id);
        }
        employee.setPassword(EMPLOYEE_PASSWORD);
        return employee;
    }

    @Override
    @Transactional
    public void updateEmployee(EmployeeDTO employeeDTO) {
        if (employeeDTO == null) {
            throw new IllegalArgumentException(EMPLOYEE_NOT_NULL);
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        lambdaUpdate()
                .eq(Employee::getId,employee.getId())
                .update(employee);
        }

}
